package com.liuya.common.listener;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * @author liuya
 * @date 20160909
 */
public class EncodingConvertFilter extends OncePerRequestFilter {
    private String fromEncoding = "ISO-8859-1";
    private String toEncoding = "UTF-8";

    @SuppressWarnings("rawtypes")
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        if (request.getMethod().equalsIgnoreCase("GET")) {
            Iterator iter = request.getParameterMap().values().iterator();
            String[] encodings;
            while (iter.hasNext()) {
                encodings = (String[]) iter.next();
                for (int i = 0; i < encodings.length; i++)
                    try {
                        encodings[i] = new String(encodings[i].getBytes(this.fromEncoding), this.toEncoding);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
            }
        }
        StringHttpMessageConverter aa = new StringHttpMessageConverter();

        request.setCharacterEncoding(this.toEncoding);
        response.setCharacterEncoding(this.toEncoding);
        filterChain.doFilter(request, response);
    }

    public String getFromEncoding() {
        return this.fromEncoding;
    }

    public void setFromEncoding(String fromEncoding) {
        this.fromEncoding = fromEncoding;
    }

    public String getToEncoding() {
        return this.toEncoding;
    }

    public void setToEncoding(String toEncoding) {
        this.toEncoding = toEncoding;
    }
}